package com.ormlite.activity.tool.button.movie;

import java.sql.SQLException;

import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.stmt.QueryBuilder;
import com.ormlite.activity.add.AbstractAddActivity;
import com.ormlite.activity.tool.DatabaseUtils;
import com.ormlite.activity.tool.GuiUtils;
import com.ormlite.activity.tool.LogUtils;
import com.ormlite.activity.tool.Utils;
import com.ormlite.db.OrmLiteHelper;
import com.ormlite.pojo.Movie;

public class AddMovieButton implements View.OnClickListener {

	private final Activity addMovieActivity;
	private final EditText[] edits;

	public AddMovieButton(AbstractAddActivity addMovieActivity, EditText... edits) {
		this.addMovieActivity = addMovieActivity;
		this.edits = edits;
	}

	@Override
	public void onClick(View v) {

		Movie movie = Movie.createMovie(edits);
		if (Utils.checkMovieFields(movie)) {
			GuiUtils.showAlertDialog(addMovieActivity, "The only field which can be empty is 'rate', try again");
			return;
		}
		LogUtils.logMovieEntity(movie);

		RuntimeExceptionDao<Movie, Integer> movieRuntimeDao = OrmLiteHelper.getMovieRuntimeDao();
		try {
			QueryBuilder<Movie, Integer> queryBuilder = buildQuery(movieRuntimeDao, movie);
			if (!queryBuilder.query().isEmpty()) {
				GuiUtils.showAlertDialog(addMovieActivity, "You can't add movie with data that arleady exists");
				return;
			}
		} catch (SQLException ex) {
			Log.e("query builder", "sql exception occured", ex);
		}
		DatabaseUtils.saveMovie(movie);
		LogUtils.logAllMovies(movieRuntimeDao.queryForAll());

		addMovieActivity.finish();
	}

	// @formatter:off
	private QueryBuilder<Movie, Integer> buildQuery(RuntimeExceptionDao<Movie, Integer> movieRuntimeDao, Movie movie)
			throws SQLException {
		QueryBuilder<Movie, Integer> queryBuilder = movieRuntimeDao.queryBuilder();
		queryBuilder
			.where()
				.eq("title", movie.getTitle())
					.and()
				.eq("year", movie.getYear());
		return queryBuilder;
	}
	// @formatter:on
}
